<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card>
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="时间范围">
                            <el-date-picker v-model="timeRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警类型">
                            <el-input v-model="queryParams.alarmType" placeholder="请输入报警类型" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警级别">
                            <el-select v-model="queryParams.alarmLevel" placeholder="请选择报警级别" clearable
                                style="width: 100%">
                                <el-option v-for="item in alarmLevelOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="处理状态">
                            <el-select v-model="queryParams.processingStatus" placeholder="请选择处理状态" clearable
                                style="width: 100%">
                                <el-option v-for="item in processingStatusOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警对象">
                            <el-input v-model="queryParams.alarmObject" placeholder="请输入报警对象" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="处理结果">
                            <el-select v-model="queryParams.handleResult" placeholder="请选择处理结果" clearable
                                style="width: 100%">
                                <el-option v-for="item in handleResultOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="mt-2">
            <!-- 操作按钮和右侧工具栏 -->
            <el-radio-group v-model="activeTab" @change="handleTabChange">
                <el-radio-button label="current">进行中报警</el-radio-button>
                <el-radio-button label="history">历史报警</el-radio-button>
            </el-radio-group>

            <!-- 数据表格 -->
            <el-table :data="alarmList" border v-loading="loading" @selection-change="handleSelectionChange"
                class="mt-2">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="alarmTime" label="报警时间" align="center" width="180" v-if="columns[0].visible" />
                <el-table-column prop="alarmType" label="报警类型" align="center" v-if="columns[1].visible" />
                <el-table-column label="报警级别" align="center" width="120" v-if="columns[2].visible">
                    <template #default="{ row }">
                        <el-tag :type="getAlarmLevelTagType(row.alarmLevel)">
                            {{ getAlarmLevelLabel(row.alarmLevel) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="alarmObject" label="报警对象" align="center" v-if="columns[3].visible" />
                <el-table-column prop="alarmDescription" label="报警描述" align="center" v-if="columns[4].visible" />
                <el-table-column label="处理状态" align="center" width="120" v-if="columns[5].visible">
                    <template #default="{ row }">
                        <el-tag :type="getProcessingStatusTagType(row.processingStatus)">
                            {{ getProcessingStatusLabel(row.processingStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right" v-if="columns[9].visible">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleDetail(row)">详情</el-button>
                        <el-button size="small" type="primary" @click="handleSingleHandle(row)"
                            v-if="row.processingStatus !== 2">
                            处理
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialog.visible" :title="detailDialog.title" width="800px"
            :close-on-click-modal="false">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="报警ID">{{ detailData.id || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警时间">{{ detailData.alarmTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警类型">{{ detailData.alarmType || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警级别">
                    <el-tag :type="getAlarmLevelTagType(detailData.alarmLevel)">
                        {{ getAlarmLevelLabel(detailData.alarmLevel) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="报警对象">{{ detailData.alarmObject || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警描述">{{ detailData.alarmDescription || '-' }}</el-descriptions-item>
                <el-descriptions-item label="处理状态">
                    <el-tag :type="getProcessingStatusTagType(detailData.processingStatus)">
                        {{ getProcessingStatusLabel(detailData.processingStatus) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="处理结果">
                    <el-tag :type="getHandleResultTagType(detailData.handleResult)">
                        {{ getHandleResultLabel(detailData.handleResult) }}
                    </el-tag>
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
                <el-button type="primary" @click="handleSingleHandle(detailData)"
                    v-if="detailData.processingStatus !== 2">
                    处理报警
                </el-button>
            </template>
        </el-dialog>

        <!-- 处理报警对话框 -->
        <el-dialog v-model="handleDialog.visible" :title="handleDialog.title" width="600px"
            :close-on-click-modal="false">
            <el-form ref="handleFormRef" :model="handleForm" :rules="handleRules" label-width="100px">
                <el-form-item label="处理结果" prop="handleResult">
                    <el-select v-model="handleForm.handleResult" placeholder="请选择处理结果" style="width: 100%">
                        <el-option v-for="item in handleResultOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="处理意见" prop="handleOpinion">
                    <el-input v-model="handleForm.handleOpinion" type="textarea" :rows="4" placeholder="请输入处理意见" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitHandle">确认处理</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RightToolbar from '@/components/RightToolbar'
import {
    getAlarmLevelList,
    getHandleResultList,
    getAlarmStatusList,
    listAlarmRecords,
    listHistoryAlarmRecords,
    getAlarmRecordDetail,
    handleAlarmRecord
} from '@/api/dispatch/call/callRecord.js'

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    alarmType: '',
    alarmLevel: undefined,
    processingStatus: undefined,
    alarmObject: '',
    handleResult: ''
})

// 时间范围选择
const timeRange = ref([])

// 表格数据
const alarmList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const showSearch = ref(true)
const activeTab = ref('current')
const handleFormRef = ref(null)
// 详情对话框控制
const detailDialog = reactive({
    visible: false,
    title: '报警记录详情'
})

// 详情数据
const detailData = ref({})

// 处理对话框控制
const handleDialog = reactive({
    visible: false,
    title: '处理报警记录',
    isBatch: false
})

// 处理表单数据
const handleForm = reactive({
    id: undefined,
    handleResult: undefined,
    handleOpinion: ''
})

// 下拉选项数据
const alarmLevelOptions = ref([])
const handleResultOptions = ref([])
const processingStatusOptions = ref([
    { id: 0, name: '未处理' },
    { id: 1, name: '处理中' },
    { id: 2, name: '已处理' }
])

// 列显隐配置
const columns = ref([
    { key: 0, label: '报警时间', visible: true },
    { key: 1, label: '报警类型', visible: true },
    { key: 2, label: '报警级别', visible: true },
    { key: 3, label: '报警对象', visible: true },
    { key: 4, label: '报警描述', visible: true },
    { key: 5, label: '处理状态', visible: true },
    { key: 6, label: '处理结果', visible: true },
    { key: 7, label: '创建人', visible: true },
    { key: 8, label: '创建时间', visible: true },
    { key: 9, label: '操作', visible: true }
])

// 表单验证规则
const handleRules = reactive({
    handleResult: [
        { required: true, message: '请选择处理结果', trigger: 'change' }
    ],
    handleOpinion: [
        { required: true, message: '请输入处理意见', trigger: 'blur' }
    ]
})

// 计算时间范围
const computedTimeRange = computed(() => {
    if (timeRange.value && timeRange.value.length === 2) {
        queryParams.startTime = timeRange.value[0]
        queryParams.endTime = timeRange.value[1]
    } else {
        queryParams.startTime = ''
        queryParams.endTime = ''
    }
})

// 获取报警级别标签
const getAlarmLevelLabel = (level) => {
    const map = {
        1: '一般',
        2: '警告',
        3: '严重'
    }
    return map[level] || level
}

// 获取报警级别标签类型
const getAlarmLevelTagType = (level) => {
    const map = {
        1: 'info',
        2: 'warning',
        3: 'danger'
    }
    return map[level] || ''
}

// 获取处理状态标签
const getProcessingStatusLabel = (status) => {
    const map = {
        0: '未处理',
        1: '处理中',
        2: '已处理'
    }
    return map[status] || status
}

// 获取处理状态标签类型
const getProcessingStatusTagType = (status) => {
    const map = {
        0: 'danger',
        1: 'warning',
        2: 'success'
    }
    return map[status] || ''
}

// 获取处理结果标签
const getHandleResultLabel = (result) => {
    const map = {
        0: '误报',
        1: '已解决',
        2: '未解决'
    }
    return map[result] || result
}

// 获取处理结果标签类型
const getHandleResultTagType = (result) => {
    const map = {
        0: 'info',
        1: 'success',
        2: 'danger'
    }
    return map[result] || ''
}

// 获取报警级别下拉列表
const fetchAlarmLevelList = async () => {
    try {
        const res = await getAlarmLevelList()
        alarmLevelOptions.value = res.data || []
    } catch (error) {
        console.error('获取报警级别列表失败:', error)
        ElMessage.error('获取报警级别列表失败')
    }
}

// 获取处理结果下拉列表
const fetchHandleResultList = async () => {
    try {
        const res = await getHandleResultList()
        handleResultOptions.value = res.data || []
    } catch (error) {
        console.error('获取处理结果列表失败:', error)
        ElMessage.error('获取处理结果列表失败')
    }
}

// 获取报警记录列表
const fetchAlarmRecords = async () => {
    try {
        loading.value = true
        computedTimeRange.value

        let res
        if (activeTab.value === 'current') {
            res = await listAlarmRecords(queryParams)
        } else {
            res = await listHistoryAlarmRecords(queryParams)
        }

        alarmList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取报警记录列表失败:', error)
        ElMessage.error('获取报警记录列表失败')
    } finally {
        loading.value = false
    }
}

// 查询按钮
const handleQuery = () => {
    queryParams.pageNum = 1
    fetchAlarmRecords()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    timeRange.value = []
    queryParams.alarmType = ''
    queryParams.alarmLevel = undefined
    queryParams.processingStatus = undefined
    queryParams.alarmObject = ''
    queryParams.handleResult = ''
    fetchAlarmRecords()
}

// 分页大小变化
const handleSizeChange = (size) => {
    queryParams.pageSize = size
    fetchAlarmRecords()
}

// 当前页码变化
const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    fetchAlarmRecords()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 标签页变化
const handleTabChange = (tab) => {
    activeTab.value = tab
    queryParams.pageNum = 1
    fetchAlarmRecords()
}

// 查看详情
const handleDetail = async (row) => {
    try {
        const res = await getAlarmRecordDetail(row.id)
        detailData.value = res.data || {}
        detailDialog.visible = true
    } catch (error) {
        console.error('获取报警记录详情失败:', error)
        ElMessage.error('获取报警记录详情失败')
    }
}

// 批量处理
const handleHandle = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    handleDialog.visible = true
    handleDialog.title = '批量处理报警记录'
    handleDialog.isBatch = true
    handleForm.id = selectedRows.value.map(item => item.id)
    handleForm.handleResult = undefined
    handleForm.handleOpinion = ''
}

// 单个处理
const handleSingleHandle = (row) => {
    handleDialog.visible = true
    handleDialog.title = '处理报警记录'
    handleDialog.isBatch = false
    handleForm.id = row.id
    handleForm.handleResult = undefined
    handleForm.handleOpinion = ''
}

// 提交处理
const submitHandle = async () => {
    try {
        await handleFormRef.value.validate()

        if (handleDialog.isBatch) {
            // 批量处理逻辑
            for (const id of handleForm.id) {
                await handleAlarmRecord({
                    id,
                    handleResult: handleForm.handleResult,
                    handleOpinion: handleForm.handleOpinion
                })
            }
            ElMessage.success('批量处理成功')
        } else {
            // 单个处理
            await handleAlarmRecord(handleForm)
            ElMessage.success('处理成功')
        }

        handleDialog.visible = false
        fetchAlarmRecords()
    } catch (error) {
        console.error('处理失败:', error)
        if (error !== 'validate') {
            ElMessage.error('处理失败')
        }
    }
}

// 导出数据
const handleExport = () => {
    ElMessage.info('导出功能待实现')
    // 这里可以添加导出逻辑
}

// 初始化加载数据
onMounted(() => {
    fetchAlarmLevelList()
    fetchHandleResultList()
    fetchAlarmRecords()
})
</script>

<style scoped>

</style>